package cn.edu.nju.software.cdiy.action.supplier;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.cdiy.bean.Supplier;
import cn.edu.nju.software.cdiy.service.SupplierService;
import cn.edu.nju.software.cdiy.util.BusinessConstant;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements SessionAware {
	
	private Map<String, Object> session;
	private SupplierService supplierService;
	private Supplier supplier;
	private String url;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setSupplierService(SupplierService supplierService) {
		this.supplierService = supplierService;
	}

	public Supplier getSupplier() {
		return supplier;
	}

	public void setSupplier(Supplier supplier) {
		this.supplier = supplier;
	}

	public String getUrl() {
		return url;
	}

	@Override
	public void validate() {
		clearFieldErrors();
	}

	@Override
	public String input() throws Exception {
		if (session.containsKey(BusinessConstant.S_SUPPLIER)) {
			return "loginAlready";
		}
		return INPUT;
	}

	@Override
	public String execute() throws Exception {
		if (session.containsKey(BusinessConstant.S_SUPPLIER)) {
			return "loginAlready";
		}
		Supplier newSupplier = supplierService.login(supplier);
		if(newSupplier == null) {
			addFieldError("login", "用户名或密码错误！");
			return ERROR;
		}
		session.put(BusinessConstant.S_SUPPLIER, newSupplier);
		url = (String) session.get(BusinessConstant.S_SUPPLIER_URL);
		return SUCCESS;
	}

}
